package com.example.javaairportflightanalysis.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.example.javaairportflightanalysis.entity.ResponseData;
import com.example.javaairportflightanalysis.service.UserService;
import com.example.javaairportflightanalysis.utils.FileUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@CrossOrigin(originPatterns = "*",allowCredentials = "true")
@RestController
@RequestMapping("/file")
public class FileController extends BaseController{

    @Autowired
    UserService userService;
//    @Value("${myfile.user.photopath}")
//    private String savePath;

//    @PostMapping("/rephoto")
//    public ResponseData<String> rePhoto(@RequestParam("userphoto")MultipartFile file, Integer id, HttpServletRequest request) throws Exception {
//        boolean result = false;
//        String fileUrl = null;
//
//        String newName = null;
//        if (null != file) {
//            // 重构上传文件的名字 : id_日期.扩展名
//            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
//            newName = id + "_" + date + FileUtil.getExtName(file.getOriginalFilename());
//            // 保存文件，得到文件保存后的URL地址
//            fileUrl = FileUtil.uploadFile(file,newName,savePath,request);
//            if (null != fileUrl) {
//                result =  true;
//            }
//        }
//
//        log.error(fileUrl);
//        ResponseData<String> responseData = new ResponseData<>();
//        responseData.setData(fileUrl);
//        if (result) {
//            responseData.setErrorCode("200");
//            responseData.setMsg("Success");
//        } else {
//            responseData.setErrorCode("605");
//            responseData.setMsg("Fail");
//        }
//        return responseData;
//    }

    @PostMapping("/upPhoto")
    public ResponseData<String> upPhoto(@RequestParam("userPhoto")MultipartFile file, Integer id,HttpServletRequest request) throws Exception {
        boolean result = false;

        String newName = null;
        if (null != file) {
            // 重构上传文件的名字 : id_日期.扩展名
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            newName = id + "_" + date + FileUtil.getExtName(file.getOriginalFilename());
            // 保存文件，得到文件保存后的URL地址
            if (null != newName) {
                result =  true;
            }
        }

//        System.out.println("hhhhhhhhh");
//        System.out.println(result);
        ResponseData<String> responseData = new ResponseData<>();
        if (result) {
            responseData.setErrorCode("200");
            responseData.setMsg("Success");

            //文件上传的地址
            String Path = ResourceUtils.getURL("classpath:").getPath() + "static/imgs";
            String realPath = Path.replace('/','\\').substring(1,Path.length());
//            System.out.println(realPath);
//            System.out.println(newName);
            File newPhoto = new File(realPath,newName);
//            System.out.println(newPhoto);
            //完成文件的上传
            file.transferTo(newPhoto);
            responseData.setData("../imgs/"+newName);
//            System.out.println(id);
//            System.out.println("session : "+request.getSession().getAttribute("LoginId"));
            userService.updateUserImg("http://localhost:8888/imgs/"+newName, (Integer) request.getSession().getAttribute("LoginId"));
            System.out.println("FileController-upPhoto:"+request.getSession().getAttribute("LoginId"));
//            System.out.println(StpUtil.getLoginId());

        } else {
            responseData.setErrorCode("605");
            responseData.setMsg("Fail");
        }
        return responseData;
    }

//    @Value("${myfile.download.path}")
//    private String downPath ;
//    @RequestMapping("/download")
//    public void download(String filename , HttpServletRequest request , HttpServletResponse response) throws Exception {
//        // 读取要下载的文件源 , File.separator是路径间隔符
//        ClassPathResource pathResource = new ClassPathResource(downPath + File.separator + filename) ;
//        System.out.println(pathResource+"----"+downPath+"----"+filename);
//        if(! pathResource.exists()) {
//            throw new Exception("要下载的文件跑了!") ;
//        }
//        // 设置响应消息头信息
//        response.setContentType("application/force-download");
//        response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename, "UTF-8"));
//        // 获取输出流 ： 写到网络，然后发送到客户端
//        OutputStream os = response.getOutputStream() ;
//        // 实例化输入流
//        FileInputStream fis = new FileInputStream(pathResource.getFile()) ;
//        // IO流操作的边读编写
//        byte[] buffer = new byte[1024] ;
//        int len = 0 ;
//        while(-1 != (len = fis.read(buffer))) {
//            os.write(buffer , 0 , len);
//        }
//        fis.close();
//        log.error("下载结束");
//    }

//    @PutMapping("/user/upPasswd")
//    public ResponseData<Object> upPasswd(@Param("Uid") Integer Uid, @Param("password") String password) {
//        System.out.println(Uid+"-----"+password);
//        System.out.println("zzzzzzzzzzzzzzzzzz");
//        return returnObject(sysUserService.updateSysUserPasswdById(password,Uid));
//    }

}
